package cc.mrbird.febs.weixin;


import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.service.RedisService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ Author 马超伟
 * @ Date 2020-11-02 18:27
 * @ Description:
 * @ Version:
 */
@Slf4j
@Component
public class WeiXinUtil extends BaseController {

    @Resource
    private RedisService redisService;

    //静态初始化当前类
    public static WeiXinUtil weiXinUtil;

    //在方法上加上注解@PostConstruct，
    // 这样方法就会在Bean初始化之后被Spring容器执行（注：Bean初始化包括，实例化Bean，并装配Bean的属性（依赖注入））。
    @PostConstruct
    public void init() {
        weiXinUtil = this;
        weiXinUtil.redisService = this.redisService;
    }

    /**
     * @ Author: 马超伟
     * @ Date: 2020/11/4 9:10
     * @ Params: []
     * @ return: java.lang.String
     * @ Description: 获取token
     */
    public static String getToken(Integer customerId) {
//        String access_token = (String) weiXinUtil.redisService.get("share:"+customerId+ ":" +"access_token");
//        log.debug("getToken.access_token==="+access_token);
//        if (access_token == null) {


        //拼接url
        StringBuilder url = new StringBuilder();
        url.append("https://api.weixin.qq.com/cgi-bin/token?");
        //appid
        url.append("grant_type=" + "client_credential");
        url.append("&appid=" + WeiXinConstant.AppId);
        url.append("&secret=" + WeiXinConstant.AppSecret);
        JSONObject jsonObj = doGetJson(url.toString());
        if (!StringUtils.isEmpty(jsonObj)) {
//            weiXinUtil.redisService.set("share:" + customerId + ":" + "access_token", jsonObj.getString("access_token"), jsonObj.getInteger("expires_in").longValue());
            return jsonObj.getString("access_token");
        }
        log.error("access_token获取失败！customerId="+customerId);
        return null;

//        }
//        return access_token;
    }

    /**
     * @ Author: 马超伟
     * @ Date: 2020/11/4 9:10
     * @ Params: [access_token]
     * @ return: cc.mrbird.febs.weixin.entity.JSTicket
     * @ Description: 获取JSTicket
     */
    public static String getJsTicket(String access_token, Integer customerId) {
//        String jsapi_ticket = (String) weiXinUtil.redisService.get("share:" + customerId + ":" + "jsapi_ticket");
//        log.debug("getJsTicket.jsapi_ticket===" + jsapi_ticket);
//        if (jsapi_ticket == null) {


            StringBuilder jsapi_ticket_url = new StringBuilder();
            jsapi_ticket_url.append("https://api.weixin.qq.com/cgi-bin/ticket/getticket?");
            jsapi_ticket_url.append("access_token=" + access_token);
            jsapi_ticket_url.append("&type=" + "jsapi");
            JSONObject jsonObj = doGetJson(jsapi_ticket_url.toString());
            if (!StringUtils.isEmpty(jsonObj)) {
//                weiXinUtil.redisService.set("share:" + customerId + ":" + "jsapi_ticket", jsonObj.getString("ticket"), jsonObj.getInteger("expires_in").longValue());
                return jsonObj.getString("ticket");
            }
            log.error("ticket获取失败！+access_token="+access_token+",customerId="+customerId);
        return null;

//        }
//        return jsapi_ticket;
    }

    /**
     * 获取时间戳(秒)
     */
    public static String getTimestamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     * 获取当前时间 yyyyMMddHHmmss
     */
    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }

    /**
     * 生成随机字符串
     */
    public static String getNonceStr() {
        String currTime = getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = buildRandom(4) + "";
        return strTime + strRandom;
    }

    /**
     * 取出一个指定长度大小的随机正整数.
     *
     * @param length int设定所取出随机数的长度。length小于11
     * @return int 返回生成的随机数。
     */
    public static int buildRandom(int length) {
        int num = 1;
        double random = Math.random();
        if (random < 0.1) {
            random = random + 0.1;
        }
        for (int i = 0; i < length; i++) {
            num = num * 10;
        }
        return (int) ((random * num));
    }


    /**
     * @ Description: 发送GET请求接口
     * @ Param: [uri]
     * @ return: com.alibaba.fastjson.JSONObject
     * @ Author: 马超伟
     * @ Date: 2020/6/10
     */
    public static JSONObject doGetJson(String uri) {
        JSONObject jsonObject = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(uri);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
                jsonObject = JSONObject.parseObject(result);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //释放链接
        get.releaseConnection();
        return jsonObject;
    }


}
